#include <iostream>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>
using namespace std;
typedef websocketpp::server<websocketpp::config::asio> wsserver_t ;

void http_handler(wsserver_t* server,websocketpp::connection_hdl hdl){
    cout<<"处理http请求"<<endl;
    wsserver_t::connection_ptr con=server->get_con_from_hdl(hdl);
    std::stringstream ss;
    ss<<"<html><body>hello world</body></html>";
    con->set_body(ss.str());
    con->set_status(websocketpp::http::status_code::ok);
}

void open_handler(wsserver_t* server,websocketpp::connection_hdl hdl){
    cout<<"连接成功"<<endl;
}

void close_handler(wsserver_t* server,websocketpp::connection_hdl hdl){
    cout<<"连接关闭"<<endl;
}

void message_handler(wsserver_t* server,websocketpp::connection_hdl hdl,wsserver_t::message_ptr msg){
    cout<<"收到消息"<<msg->get_payload()<<endl;
    //收到消息将相同的消息发回给websocketpp客户端
    server->send(hdl,msg->get_payload(),websocketpp::frame::opcode::text);
}

int main()
{
    //使用websocketpp库创建服务器
    wsserver_t srv;
    //设置websocketpp打印日志等级
    //all表示全部都打印
    //none表示什么日志都不打印
    srv.set_access_channels(websocketpp::log::alevel::none);
    //初始化asio
    srv.init_asio();
    /*设置启⽤地址重⽤*/
    srv.set_reuse_addr(true);
    //注册http请求函数
    srv.set_http_handler(std::bind(http_handler,&srv,std::placeholders::_1));
    // 注册websocket请求的处理函数
    srv.set_open_handler(std::bind(open_handler,&srv,std::placeholders::_1));
    srv.set_close_handler(std::bind(close_handler,&srv,std::placeholders::_1));
    srv.set_message_handler(std::bind(message_handler,&srv,std::placeholders::_1,std::placeholders::_2));

    //监听8080端口
    srv.listen(8080);
    //开始接收tcp连接
    srv.start_accept();
    //开始运行服务器
    srv.run();
    return 0;
}








